package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.Data;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
@RabbitListener(queues = "order.release.order.queue")
public class OrderCloseListener {

    @Autowired
    OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity entity, Channel channel, Message message) throws IOException {
        try{
        //库存回滚条件 订单创建中途其他服务出错回滚/或者订单没有支付状态码是4
            //问题，若是订单系统由于机器卡顿，消息延迟，没有将状态改为取消，那么这个订单 库存将永远不会解锁
            //解决方法，订单若是释放了，再次主动发个消息，让库存系统再确认一次解锁库存
            System.out.println("开始关闭订单");
            orderService.closeOrder(entity);
            //手动调用支付宝的收单功能

            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
